<?php

namespace addons\rexam\controller;

use think\Session;

class Rexam extends Base
{
    public $one = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\rexam\Rexam;
    }

    /**
     * 考试id
     */
    protected function check_id(){
        $param = input();
        if(empty($param['id'])){
            $url = addon_url('rexam/index/index');
            $this->redirect($url);
        }
        $this->one = $this->model->get(['id' => $param['id']]);
        if(empty($this->one)){
            $url = addon_url('rexam/index/index');
            $this->redirect($url);
        }
        return $param['id'];
    }

    public function index(){
        $rid = $this->check_id();
        $current_time = time();
        $answer_model = new \app\admin\model\rexam\Answer;
        $answer = $answer_model->where(['user_id'=>$this->auth->id, 'rexam_id'=>$rid])->find();

        if($this->one['starttime']>=$current_time){
            $this->one['rexam_status'] = 0;//未开始
        }elseif($this->one['expiretime']<=$current_time) {
            if($answer) {
                $this->assign("answer", $answer);
                $this->assign("points", $answer['points']);
                if ($answer['overtime']) {
                    $this->one['rexam_status'] = 5;//已结束，已交答卷
                } else {
                    $this->one['rexam_status'] = 4;//已结束，未交答卷
                }
            }else {
                $this->one['rexam_status'] = 4;//已结束，未交答卷
            }
        }else{
            if($answer) {
                $this->assign("answer", $answer);
                $this->assign("points", $answer['points']);
                if ($answer['overtime']) {
                    $this->one['rexam_status'] = 3;//已完成
                } else {
                    $this->one['rexam_status'] = 2;//答题中
                }
            }else {
                $this->one['rexam_status'] = 1;//已开始，未答卷
            }
        }

        $this->assign("one",$this->one);
        $this->assign("title",$this->one['name']);
        return $this->view->fetch();
    }

    protected function check_group($group_id){
        $group_model = new \app\admin\model\rexam\Group;
        $group_ids = $group_model->idchain($this->rexam_user['rexam_group_id']);
        if(in_array($group_id, $group_ids)) {
            return true;
        }else{
            return false;
        }
    }

    protected function check_bind($bind_ids){
        $info_model = new \app\admin\model\rexam\Info;
        $where = array();
        $where['user_id']=$this->auth->id;
        $where['rexam_bind_id']=array('in', $bind_ids);
        $info = $info_model->where($where)->select();
        if(count($info) !== count(explode(',',$bind_ids))){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 信息绑定
     */
    public function bind(){
        $info_model = new \app\admin\model\rexam\Info;
        $bind_model = new \app\admin\model\rexam\Bind;
        if ($this->request->isAjax()) {
            $param = input();
            $data = array();
            foreach ($param as $key => $vo){
                if(substr( $key,0,4) == 'bind'){
                    $data[substr($key, 4)]=$vo;
                }
            }
            foreach ($data as $key => $vo){
                $info_one = $info_model->where(['rexam_bind_id'=>$key,'user_id'=>$this->auth->id])->find();
                if($info_one){
                    $info_model->allowField(true)->save(['value'=>$vo], ['rexam_bind_id'=>$key,'user_id'=>$this->auth->id]);
                }else{
                    $info_model->allowField(true)->create(['rexam_bind_id'=>$key,'user_id'=>$this->auth->id,'value'=>$vo]);
                }
            }
            return $this->ajax_success('更新成功!',$data);
        }
        $rid = $this->check_id();
        $url = addon_url('rexam/rexam/go',['id' => $rid]);
        $this->assign("url",$url);
        if(!$this->one['binddata']){
            $this->redirect($url);
        }
        $this->assign("one",$this->one);
        $bind_info = array();
        $bind_ids = explode(',', $this->one['rexam_bind_ids']);
        $where = array();
        $where['user_id']=$this->auth->id;
        foreach ($bind_ids as $vo){
            $where['rexam_bind_id']=$vo;
            $value = $info_model->where($where)->find();
            $bind_src = $bind_model->where(['id'=>$vo])->field('id,name,typedata,optionjson')->find();
            $bind_info[] = ['id'=>$vo, 'name'=>$bind_src['name'], 'typedata'=>$bind_src['typedata'], 'value'=>empty($value)?'':$value['value'], 'option'=>json_decode($bind_src['optionjson'],true)];
        }
        $this->assign("bind_info",$bind_info);
//        var_dump($bind_info);
//        exit();
        return $this->view->fetch();
    }

    protected function build(){
        $answer_model = new \app\admin\model\rexam\Answer;
        $question_model = new \app\admin\model\rexam\Question;
        $where = array();
        if($this->one['areadata'] == 2){
            $where['id'] = array('in', $this->one['rexam_question_ids']);
        }elseif($this->one['areadata'] == 1){
            $where['rexam_subject_id'] = array('in', $this->one['rexam_subject_ids']);
        }else{
            $where['id'] = array('gt', 0);
        }
        $temp_question_list = $question_model->field('id')->where($where)->select();
        $question_count = count($temp_question_list);// //获取总记录数
        if ($question_count < $this->one['question_count']) {
            $this->error('题目数量不足，请联系管理员');
        }
        $i = 0;
        $question_list = array();
        while($i<$this->one['question_count']){
            $rund_question = $temp_question_list[rand(0, $question_count - 1)]['id'];
            if (!in_array($rund_question, $question_list)) {
                $question_list[] = $rund_question;
                $i++;
            }
        }

        $data = array();
        $data['user_id'] = $this->auth->id;
        $data['rexam_id'] = $this->one['id'];
        $data['rexamquestion_ids'] = implode(',', $question_list);
        $data['question_count'] = $this->one['question_count'];
        $data['begintime'] = time();
        $answer_model->create($data);
        return $data;
    }

    public function clear(){
        $param = input();
        Session::delete('rexam_'.$param['id']);
        $url = addon_url('rexam/rexam/go',['id'=>$param['id']]);
        $this->redirect($url);
    }

    /**
     * 答题
     */
    public function go(){
        $rid = $this->check_id();
        $current_time = time();
        if($this->one['starttime']>=$current_time){
            $this->error('开始时间是：'.datetime($this->one['starttime'], 'Y-m-d H:i:s'));
        }elseif($this->one['expiretime']<=$current_time) {
            $this->error('已经截止了');
        }
        if($this->one['groupdata']){
            if(!$this->check_group($this->one['rexam_group_id'])){
                $this->error('您所在群组无答题权限');
            };
        }
        if($this->one['binddata']){
            if(!$this->check_bind($this->one['rexam_bind_ids'])){
                $url = addon_url('rexam/rexam/bind',['id' => $rid]);
                $this->redirect($url);
            };
        }
        $this->assign("one",$this->one);
        $answer_model = new \app\admin\model\rexam\Answer;
        $answer = $answer_model->where(['user_id'=>$this->auth->id,'rexam_id'=>$rid])->find();
        $answer_one = array();
        if(empty($answer)){
            $answer = $this->build();
            $url = addon_url('rexam/rexam/go',['id' => $rid]);
            $this->redirect($url);
        }elseif($answer['overtime']){
            $url = addon_url('rexam/rexam/index',['id' => $rid]);
            $this->redirect($url);
        }

        $question = explode(',', $answer['rexamquestion_ids']);
        if(empty($answer['answerjson'])){
            foreach ($question as $vo){
                $answer_one[$vo]=['css'=>'','value'=>''];
            }
        }else{
            $answerarr = json_decode($answer['answerjson'], true);
            foreach ($answerarr as $vo){
                $answer_one[$vo['qid']]=['css'=>'done','value'=>$vo['ans']];
            }
        }
        $this->assign("answer_one",$answer_one);
        $this->assign("question",$question);
        $this->assign("answer",$answer);
        $this->assign("title",$this->one['name']);

        $url = addon_url('rexam/rexam/index',['id' => $rid]);
        $this->assign("url",$url);
        
        return $this->view->fetch();
    }

    public function ana(){
        $rid = $this->check_id();
        if(empty($this->one['anadata'])) {
            $this->error('未开放答卷解析');
        }

        $current_time = time();
        if($this->one['expiretime']>=$current_time) {
            $this->error('截止后才能进行答卷解析');  //这里注释掉则完成答题后随时可以看解析
        }
        $answer_model = new \app\admin\model\rexam\Answer;
        $answer = $answer_model->where(['user_id'=>$this->auth->id,'rexam_id'=>$rid])->find();
        if(empty($answer)||empty($answer['overtime'])){
            $this->error('未找到您的答卷');
        }
        $this->assign("one",$this->one);
        
        $answer_one = array();
        $question = explode(',', $answer['rexamquestion_ids']);
        $answerarr = json_decode($answer['answerjson'], true);
        foreach ($answerarr as $vo){
            if($vo['res']){
                $css = 'right';
            }else{
                $css = 'wrong';
            }
            $answer_one[$vo['qid']]=['css'=>'done '.$css,'value'=>$vo['ans'], 'res'=>$vo['res']];
        }

        $this->assign("answer_one",$answer_one);
        $this->assign("question",$question);
        $this->assign("answer",$answer);
        $this->assign("title",$this->one['name']);

        $url = addon_url('rexam/rexam/index',['id' => $rid]);
        $this->assign("url",$url);

        return $this->view->fetch();
    }

}